<template>
  <!-- 单曲 -->
  <div class="single">
    <div class="checkAll">
      <el-button
        type="primary"
        size="small"
        @click="handleCheckAllChange"
        v-text="checkAll ? $t('main.deselectAll') : $t('main.selectAll')"
      ></el-button>
      <el-button
        @click="openConfirm('cancelCompositions')"
        class="clearBtn"
        size="small"
        icon="el-icon-delete-solid"
        >{{ $t("public.delete") }}</el-button
      >
    </div>
    <div class="table-box">
      <el-table
        class="singleTable"
        ref="songListTable"
        :data="list"
        highlight-current-row
        @selection-change="handleSelectionChange"
        v-loading="fullscreenLoading"
        v-el-table-infinite-scroll="load"
        infinite-scroll-disabled="isPage"
        infinite-scroll-delay="120"
        infinite-scroll-immediate="false"
        height="100%"
        :size="isMobile ? 'mini' : 'medium'"
      >
        <el-table-column type="selection" min-width="100"> </el-table-column>
        <!-- 播放按钮 -->
        <el-table-column
          v-if="isMobile"
          :label="$t('main.NOSingleName')"
          min-width="180"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <div
              class="singName ellipsis"
              :class="
                currentSong.trackId == scope.row.trackId && playing
                  ? 'playing'
                  : ''
              "
              @click="play('songList', scope.row)"
            >
              <span class="row-index">
                <span class="playIndex">{{ scope.$index + 1 }}</span>
                <img
                  src="@/assets/images/playGif.gif"
                  class="playGif pointer"
                />
                <svg-icon name="pause" class="icon icon-pause" />
              </span>
              <!-- <svg-icon name="play" class="icon playGif"/> -->
              <span
                v-text="
                  $i18n.locale === 'zh'
                    ? scope.row.trackCtitle || scope.row.trackTitle
                    : scope.row.trackTitle
                "
              ></span>
            </div>
          </template>
        </el-table-column>
        <template v-else>
          <!-- 播放按钮 -->
          <el-table-column min-width="30">
            <template slot-scope="scope">
              <div
                :class="
                  currentSong.trackId == scope.row.trackId && playing
                    ? 'playing'
                    : ''
                "
              >
                <svg-icon
                  @click="play('pause', scope.row)"
                  name="pause"
                  class="icon icon-pause"
                />
                <svg-icon
                  @click="play('play', scope.row)"
                  name="play"
                  class="icon icon-play"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('main.NOSingleName')"
            min-width="200"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span>{{ scope.$index + 1 }}</span>
              <span
                class="singleName"
                v-text="
                  $i18n.locale === 'zh'
                    ? scope.row.trackCtitle || scope.row.trackTitle
                    : scope.row.trackTitle
                "
              ></span>
            </template>
          </el-table-column>
        </template>
        <el-table-column
          min-width="160"
          :label="$t('main.albumName')"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span
              v-text="
                $i18n.locale === 'zh'
                  ? scope.row.musicAlbum.catalogueCname ||
                    scope.row.musicAlbum.catalogueName
                  : scope.row.musicAlbum.catalogueName
              "
            ></span>
          </template>
        </el-table-column>
        <el-table-column
          min-width="50"
          :label="$t('public.download')"
          align="center"
        >
          <template slot-scope="scope">
            <svg-icon
              @click="dialogDownload('download', scope.row)"
              name="download"
              class="icon icon-download"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="timing"
          min-width="80"
          show-overflow-tooltip
          :label="list.totalTime ? list.totalTime : $t('main.duration')"
        ></el-table-column>
        <el-table-column min-width="50">
          <template slot-scope="scope">
            <span
              @click="openConfirm('cancelComposition', scope.row.trackId)"
              class="icon el-icon-delete-solid"
            ></span>
          </template>
        </el-table-column>
        <p class="el-icon-loading"></p>
      </el-table>
    </div>
    <div class="page-wrap" v-show="isPage">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pageNum"
        :page-size="params.pageSize"
        background
        hide-on-single-page
        layout="total, prev, pager, next, jumper"
        :total="total"
        :small="isMobile"
      >
      </el-pagination>
    </div>

    <!--弹窗界面-->
    <el-dialog
      width="20%"
      :title="$t(textMap[dialogStatus])"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <!-- 下载弹窗 -->
      <el-form
        v-if="dialogStatus == 'download'"
        :model="download"
        class="download"
        :rules="downloadFromRules"
        ref="download"
      >
        <el-form-item :label="$t('public.account')" prop="account">
          <el-input
            v-model="download.account"
            :placeholder="$t('public.enterAccount')"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('public.password')" prop="password">
          <el-input
            v-model="download.password"
            show-password
            :placeholder="$t('public.enterPassword')"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="clearBtn" @click.native="dialogFormVisible = false">{{
          $t("public.cancel")
        }}</el-button>
        <el-button type="primary" @click="createData(dialogStatus)">{{
          $t("public.save")
        }}</el-button>
      </div>
    </el-dialog>
    <!-- <drawer-list :isPlayer="true"></drawer-list> -->
    <!-- <div class="fixed-aplayer">
      <a-player
        :playInfo="playInfo"
        :playList="playList"
        class="a-player"
      />
    </div> -->
  </div>
</template>

<script>
// import drawerList from "@/components/common/drawerList/Index";
// import aPlayer from "@/components/common/aPlayer/Index";
import elTableInfiniteScroll from "el-table-infinite-scroll";
import { mapMutations, mapGetters, mapActions } from "vuex";
export default {
  directives: {
    "el-table-infinite-scroll": elTableInfiniteScroll,
  },
  data() {
    return {
      list: [], //列表数据
      // 是否显示加载动画
      loading: false,
      // 请求参数
      params: {
        // userId: this.$store.getters.userInfo.userId,
        // useType: 3,
        // token: localStorage.getItem("token"),
        // 返回数量
        pageSize: 20,
        // 当前页数
        pageNum: 1,
      },
      isPage: false, //是否显示分页 / 加载更多
      total: 0, //总条数
      multipleSelection: [], //多选 选中项
      currentRow: null, // 当前选中行
      avtiveId: "", // 当前选中行单曲id
      dialogFormVisible: false, //弹窗
      dialogStatus: "", //编辑框界面切换
      fullscreenLoading: false, //数据载入动画
      textMap: {
        //添加与编辑界面
        download: "public.passwordAuthentification", //this.$t('public.edit')
      },
      //弹窗界面数据
      download: {
        roleId: "0", //待定
        account: "",
        password: "",
      },
      downParams: {}, // 下载参数
      // 获取要下载的单曲信息
      currentSingle: {
        name: "", // 单曲名(文件名)
        trackId: "", //单曲ID
        quality: "", //音质：320、192、hifi
      },
    };
  },
  components: {
    // drawerList,
    // aPlayer,
  },
  computed: {
    ...mapGetters([
      "loginStatu",
      "userInfo",
      "playing",
      "currentSong",
      "playLists",
      "isMobile",
      "isAndOrIos",
    ]),
    checkAll() {
      return (
        this.multipleSelection.length === this.list.length &&
        this.list.length > 0
      );
    },
    downloadFromRules() {
      return {
        account: [
          {
            required: true,
            message: this.$t("public.accountEmpty"),
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: this.$t("public.passwordEmpty"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  watch: {},
  created() {},
  mounted() {
    this.getData();
  },
  methods: {
    ...mapMutations({
      setPlayList: "SET_PLAYLIST",
      setDialogLogin: "SET_DIALOGLOGIN",
      setPlayParentId: "SET_PLAY_PARENT_ID",
      setPlayClipId: "SET_PLAY_CLIP_ID",
    }),
    ...mapActions([
      // 点击选择播放
      "selectPlay",
      // 点击播放全部
      "playAll",
      "playStatus",
      "savePlayList",
      "clearPlayList",
    ]),
    //分页 每页条数
    handleSizeChange(val) {
      this.params.pageSize = val;
      this.getData();
    },
    //当前页
    handleCurrentChange(val) {
      this.params.pageNum = val;
      this.list = [];
      this.getData();
    },
    async getData() {
      this.fullscreenLoading = true;
      try {
        let res = await this.$api.user.getCompositionList(this.params);
        if (res.code === 1000000) {
          this.list = res.source ? res.source : [];
          this.total = res.total;
          this.fullscreenLoading = false;
          if (res.size < 50 && res.size < res.total) {
            this.loading = true;
            this.isPage = false;
          } else {
            this.loading = false;
            this.isPage = true;
          }
        } else {
          this.fullscreenLoading = false;
          this.list = [];
        }
      } catch (e) {
        console.log(e);
      }
    },
    //全选
    handleCheckAllChange() {
      if (this.checkAll) {
        this.$refs.songListTable.clearSelection();
      } else {
        this.list.forEach((row) => {
          this.$refs.songListTable.toggleRowSelection(row, true);
        });
      }
    },
    //多选事件
    handleSelectionChange(val) {
      // let checkedCount = val.length;
      // this.checkAll = checkedCount === this.list.length && checkedCount;
      // this.isIndeterminate =
      //   checkedCount > 0 && checkedCount < this.list.length;
      this.multipleSelection = val;
    },
    // 删除 全部/部分
    openConfirm(type, trackId) {
      if (!this.loginStatu) {
        this.setDialogLogin(true);
        // this.$notify.error({
        //   title: this.$t("public.sorry"),
        //   message: this.$t("public.loginPermission"),
        //   duration: 3000,
        // });
        return;
      }
      if (type == "cancelCompositions" && this.multipleSelection.length == 0) {
        this.$message({
          showClose: true,
          message: this.$t("public.selectDeleteSingle"),
          type: "warning",
          duration: 1500,
        });
        return;
      }
      // if(type == "cancelCompositions" && this.multipleSelection.length)
      let text = "";
      if (type == "cancelComposition" || type == "cancelCompositions") {
        // if (this.currentSong.trackId === trackId && this.playing) {
        //   this.$message({
        //     message: this.$t("public.cannotDeleteCurrentlyPlaying"),
        //     offset: 46,
        //     type: "warning",
        //     duration: 2000,
        //   });
        //   return;
        // }
        text = this.$t("public.noLike");
      }
      this.$confirm(text, {
        confirmButtonText: this.$t("public.confirm"),
        cancelButtonText: this.$t("public.cancel"),
        showClose: false,
        center: true,
      })
        .then(async () => {
          let playList = [];
          if (type == "cancelCompositions") {
            // 播放列表包含 当前播放歌曲
            let idx;
            const flag = this.multipleSelection.some((item, index) => {
              if (item.trackId === this.currentSong.trackId) {
                idx = index;
                return true;
              }
            });
            // 包含并播放状态 -不清空
            if (flag && this.playing) {
              if (this.multipleSelection.length == 1) {
                this.$message({
                  message: this.$t("public.cannotDeleteCurrentlyPlaying"),
                  offset: 46,
                  type: "warning",
                  duration: 1500,
                  showClose: true,
                });
                return false;
              }
              this.multipleSelection.splice(idx, 1);
              // 设置播放列表为当前播放歌曲(循环播放)
              this.selectPlay({
                list: [this.currentSong],
                index: this.currentSong.trackId,
              });
            } else if (flag) {
              this.selectPlay({
                list: [],
                index: "0",
              });
            }
            let params = {
              type: 1,
              contentIds: this.multipleSelection.map((item) => {
                return item["trackId"];
              }),
              selectState:
                this.multipleSelection.length == this.list.length ? 1 : 2,
            };
            await this.$api.user.cancelComposition(params);
            playList = (this.playLists || []).map((val) => {
              this.multipleSelection.map((i) => {
                if (val.trackId == i.trackId) {
                  val.likeState = 0;
                }
                return i;
              });
              return val;
            });
          } else if (type == "cancelComposition") {
            if (this.currentSong.trackId === trackId) {
              this.$message({
                message: this.$t("public.cannotDeleteCurrentlyPlaying"),
                offset: 46,
                type: "warning",
                duration: 1500,
                showClose: true,
              });
              return false;
              // this.selectPlay({
              //   list: [],
              //   index: "0",
              // });
            }
            let params = {
              type: 1,
              contentIds: [trackId],
              selectState: 2, //未全选
            };
            await this.$api.user.cancelComposition(params);
            playList = (this.playLists || []).map((val) => {
              if (val.trackId == trackId) {
                val.likeState = 0;
              }
              return val;
            });
          }
          this.$message({
            showClose: true,
            type: "success",
            message: this.$t("public.successfullyDelete"),
            duration: 1500,
          });
          this.getData();
          localStorage.setItem("__playList__", JSON.stringify(playList));
        })
        .catch((err) => {
          console.log(err);
          // this.$message({
          //   type: "info",
          //   message: "已取消操作",
          // });
        });
    },
    async play(type, item) {
      // let arr = [];
      // let list = arr.concat(...this.detailData.works.filter(item=>Boolean(item.compositions)).map(item=>item.compositions));
      if (type == "play") {
        this.savePlayList({ list: this.list, location: "start" });
        this.selectPlay({
          list: this.playLists,
          index: item.trackId,
        });
        this.setPlayParentId(null);
        this.setPlayClipId(null);
      } else if (type == "pause") {
        this.playStatus(false);
      } else if (type == "songList") {
        if (this.currentSong.trackId == item.trackId && this.playing) {
          this.playStatus(false);
        } else {
          this.savePlayList({ list: this.list, location: "start" });
          this.selectPlay({
            list: this.playLists,
            index: item.trackId,
          });
          this.setPlayParentId(null);
          this.setPlayClipId(null);
        }
      }
      // this.avtiveId = val.trackId;
      // let params = {
      //   trackId: val.trackId,
      //   quality: val.hifi == 1 ? "hifi" : val.kbps320 == 1 ? "320" : val.kbps192 == 1 ? "192" : val.kbps64 ? "64" : "",
      //   terminal: "Web",
      // }
      // let res = await this.$api.user.musicAddress(params);
      // this.playInfo = {
      //   title: this.$i18n.locale === 'zh' ? val.trackCtitle||val.trackTitle : val.trackTitle,
      //   artist: val.composer ? this.$i18n.locale === 'zh' ? val.composer.fullCname||val.composer.fullName : val.composer.fullName : "",
      //   src: res.data,
      // }
      // console.log(this.playInfo)
    },
    //下载
    async dialogDownload(type, item) {
      if (!this.loginStatu) {
        this.setDialogLogin(true);
        return;
      }
      this.dialogStatus = type;
      if (type == "download") {
        if (this.isMobile) {
          if (this.isAndOrIos === "android") {
            let ele = document.createElement("a");
            ele.download =
              this.$i18n.locale === "zh"
                ? "库克音乐图书馆.apk"
                : "KUKE Music Library.apk";
            ele.style.display = "none";
            ele.href = "https://hoss.kuke.com/kuke-package/app-release.apk";
            document.body.appendChild(ele);
            ele.click();
            document.body.removeChild(ele);
          } else if (this.isAndOrIos === "ios") {
            this.$notify.info({
              title: this.$t("public.tips"),
              message: this.$t("home.comingSoon"),
              offset: 100,
              duration: 1000,
            });
          }
        } else {
          this.downParams = {
            downloadType: 511,
            contents: [
              {
                contentId: item.trackId,
                moduleId: item.musicAlbum.moduleId,
              },
            ],
            theWay: 2, //1账号下载，2非账号下载
          };
          this.downInfo(this.downParams, "download", item);
        }
      }
    },
    // 保存不同下载信息
    async downInfo(params, type, item) {
      if (type == "download" && item) {
        // 保存当前下载单曲信息
        this.currentSingle.name =
          this.$i18n.locale === "zh"
            ? item.trackCtitle || item.trackTitle
            : item.trackTitle;
        this.currentSingle.trackId = item.trackId;
        this.currentSingle.quality =
          item.hifi == 1
            ? "hifi"
            : item.kbps320 == 1
            ? "320"
            : item.kbps192 == 1
            ? "192"
            : item.kbps64
            ? "64"
            : "";
      }
      let res = await this.$api.user.userDownloadCheck(params);
      // 不需要账密(不弹框)
      if (res.code === 1000000) {
        this.dialogFormVisible = false;
        this.createData(type);
      } else if (res.code === 1701001) {
        this.$message({
          showClose: true,
          message: this.$t("public.downFailed"),
          type: "error",
          duration: 1500,
        });
      } else if (res.code === 1701002) {
        // 需要账密弹框
        this.dialogFormVisible = true;
        // 如果打开弹框 重置表单规则
        this.$nextTick(() => {
          this.$refs[type].resetFields();
        });
        this.downParams.theWay = 1;
      } else if (res.code === 1701003) {
        this.$message({
          showClose: true,
          message: this.$t("public.downBalanceInsufficient"),
          type: "error",
          duration: 1500,
        });
      } else if (res.code === 1701004) {
        this.$message({
          showClose: true,
          message: this.$t("public.accountPasswordIncorrect"),
          type: "error",
          duration: 1500,
        });
      } else if (res.code === 1000002) {
        this.$notify({
          title: this.$t("public.warning"),
          message:
            item.musicAlbum.moduleId == 516
              ? this.$t("public.classicalValidityExpires")
              : item.musicAlbum.moduleId == 518
              ? this.$t("public.worldNationValidityExpires")
              : item.musicAlbum.moduleId == 580
              ? this.$t("public.JazzValidityExpires")
              : item.musicAlbum.moduleId == 517
              ? this.$t("public.audioBooksValidityExpires")
              : this.$t("public.moduleValidityExpires"),
          type: "warning",
          offset: 100,
        });
      }
    },
    //弹窗 提交按钮
    async createData(type) {
      // 需要输入账密验证
      if (this.dialogFormVisible) {
        this.$refs[type].validate(async (valid) => {
          if (valid) {
            if (type == "download") {
              this.downParams.account = this.download.account;
              this.downParams.password = this.download.password;
              this.downInfo(this.downParams, type);
              return false;
            }
          }
        });
      } else {
        if (type == "download") {
          let params = {
            trackId: this.currentSingle.trackId,
            quality: this.currentSingle.quality,
            terminal: "Web",
          };
          let res = await this.$api.user.musicAddress(params);
          if (res.data) {
            this.dialogFormVisible = false;
            this.$message({
              showClose: true,
              message: this.$t("public.downloading"),
              duration: 1500,
            });
            this.utils.downRow(res.data, this.currentSingle.name, "mp3");
          } else {
            this.$message({
              showClose: true,
              message: this.$t("public.addressFailed"),
              type: "error",
              duration: 1500,
            });
          }
        }
      }
    },
    // 加载更多
    load() {
      this.params.pageSize += 15;
      this.getData();
    },
  },
};
</script>

<style lang="scss" scoped>
.single {
  // margin-bottom: 180px;
  .table-box {
    width: 100%;
    height: 400px;
    // min-height: 400px;
    .singleName {
      margin-left: 16px;
    }
    .icon-pause {
      display: none;
    }
    .playing {
      .icon-pause {
        display: flex;
      }
      .icon-play {
        display: none;
      }
    }
  }
}
</style>
